package com.jh.paymentchannel.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.Spend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jh.paymentchannel.business.SpendBusiness;

import cn.jh.common.utils.CommonConstants;


@Controller
public class SpendService {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    SpendBusiness spendBusiness;

    //	增加一条记录
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/add")
    public @ResponseBody
    Object addSpend(HttpServletRequest request,
                    @RequestParam(value = "status", required = false, defaultValue = "") String status,
                    @RequestParam(value = "amount", required = false, defaultValue = "") String amount,
                    @RequestParam(value = "payCard", required = false, defaultValue = "") String payCard,
                    @RequestParam(value = "batchNo", required = false, defaultValue = "") String batchNo,
                    @RequestParam(value = "userId", required = false, defaultValue = "") String userId,
                    @RequestParam(value = "bindId", required = false, defaultValue = "") String bindId,
                    @RequestParam(value = "message", required = false, defaultValue = "") String message,
                    @RequestParam(value = "orderSon", required = false, defaultValue = "") String orderSon,
                    @RequestParam(value = "executionTime", required = false, defaultValue = "") String sexecutionTime,
                    @RequestParam(value = "orderCode") String orderCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        Date executionTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (!"".equals(amount)) {
                Double.valueOf(amount);
            }
            if (!"".equals(sexecutionTime)) {
                executionTime = sdf.parse(sexecutionTime);
            }
            if (status.length() > 1) {
                throw new RuntimeException("status超过长度");
            }
        } catch (Exception e) {
            LOG.error("/r/n非法输入异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.非法输入,请检查参数");
            return map;
        }
        Spend model = new Spend();
        model.setAmount(amount.trim());
        model.setBatchNo(batchNo.trim());
        model.setExecutionTime(executionTime);
        model.setOrderCode(orderCode.trim());
        model.setPayCard(payCard.trim());
        model.setStatus(status.trim());
        model.setBindId(bindId);
        model.setUserId(userId);
        model.setMessage(message);
        try {
            model = spendBusiness.addOne(model);
        } catch (Exception e) {
            LOG.error("/r/n保存模型异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.保存数据出错了哦,请重试");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.添加成功");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/findbybindid")
    public @ResponseBody
    String findByBindId(@RequestParam(value = "bindId") String bindId) {
        List<Spend> spend;
        String lasttime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            spend = spendBusiness.findBybindId(bindId.trim());
            for (int i = 0; i < spend.size(); i++) {
                Spend s = spend.get(i);
                if (spend.size() > 1) {
                    if (spend.get(i).getAmount().equals("2.00")) {
                        if ("绑卡首次支付验证".equals(s.getMessage().trim()) || "FAILED".equals(s.getMessage().trim())) {
                            lasttime = sdf.format(spend.get(i).getExecutionTime());
                        }
                    }
                } else {
                    if ("绑卡首次支付验证".equals(s.getMessage().trim()) || "FAILED".equals(s.getMessage().trim())) {
                        return sdf.format(s.getExecutionTime());
                    }
                }
            }
        } catch (Exception e) {
            return "error";
        }
        if (null != lasttime)
            return lasttime;
        if (spend.isEmpty()) {
            return null;
        }
        return null;

    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/findbyorderson")
    public @ResponseBody
    Object findById(@RequestParam(value = "orderSon") String orderSon) {
        Map<String, Object> map = new HashMap<>();
        Spend spend;
        try {
            spend = spendBusiness.findByorderSon(orderSon.trim());
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, e.getMessage());
            return map;
        }
        if (spend == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询数据为空");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "查询成功");
        map.put("result", spend);
        return map;

    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/findbyuserid")
    public @ResponseBody
    Object findByUserId(@RequestParam(value = "userId") String userId) {
        Map<String, Object> map = new HashMap<>();
        List<Spend> spend;
        try {
            spend = spendBusiness.findByUserId(userId.trim());
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, e.getMessage());
            return map;
        }
        if (spend == null || spend.isEmpty()) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询数据为空");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "查询成功");
        map.put("result", spend);
        return map;

    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/delete/byordercode")
    public @ResponseBody
    Object deleteByOrderCode(@RequestParam(value = "orderCode") String orderCode
    ) {
        Map<String, Object> map = new HashMap<>();
        List<Spend> models;
        try {
            models = spendBusiness.findByOrderCode(orderCode.trim());
        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.WAIT_CHECK);
            map.put(CommonConstants.RESP_MESSAGE, "数据错误");
            return map;
        }
        try {
            for (int i = 0; i < 2; i++) {
                if (!models.get(i).getStatus().equals("0")) {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                    map.put(CommonConstants.RESP_MESSAGE, "不能删除，子任务已执行!");
                    return map;
                } else {
                    //spendBusiness.delete(models.get(i));
                    Spend spend = models.get(i);
                    spend.setStatus("9");
                    spendBusiness.save(spend);
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.WAIT_CHECK);
            map.put(CommonConstants.RESP_MESSAGE, "数据错误");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "删除任务成功");
        return map;

    }

    //	根据ordercode查询
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/find/byordercode")
    public @ResponseBody
    Object querySpends(
            @RequestParam(value = "orderCode") String orderCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Spend> models = null;
        try {
            if (null == orderCode || orderCode.isEmpty()) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "参数不能为空");
                return map;
            }
            models = spendBusiness.findByOrderCode(orderCode.trim());
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }

        if (models == null || models.size() < 1) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.查询成功!");
        map.put(CommonConstants.RESULT, models);
        return map;
    }

    //根据时间查询当前还款任务的消费子任务
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/find/bytime")
    public @ResponseBody
    Object querySpendsbyTime(
            @RequestParam(value = "start") String start,
            @RequestParam(value = "end") String end) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Spend> models = null;
        try {
            models = spendBusiness.findByExecutionTime(start, end);
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }

        if (models == null || models.size() < 1) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.查询成功!");
        map.put(CommonConstants.RESULT, models);
        return map;
    }

    //根据时间查询当前还款任务已经失败的消费子任务
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/find/bytimeandstatus")
    public @ResponseBody
    Object querySpendsbyTimeandStatus(
            @RequestParam(value = "start") String start,
            @RequestParam(value = "end") String end) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Spend> models = null;
        try {
            models = spendBusiness.findByExecutionTimeandStatus(start, end);
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }

        if (models == null || models.size() < 1) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.查询成功!");
        map.put(CommonConstants.RESULT, models);
        return map;
    }

    /*根据ordercode和amount修改status*/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/update/byordercode")
    public @ResponseBody
    Object updateSpendsByOrderCodeAndAmount(
            @RequestParam(value = "orderCode") String orderCode,
            @RequestParam(value = "amount") String amount,
            @RequestParam(value = "message") String message,
            @RequestParam(value = "status") String status
    ) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Double.valueOf(amount);
            if (status.length() > 1) {
                throw new RuntimeException("status超过长度");
            }
        } catch (Exception e) {
            LOG.error("/r/n输入非法输入异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.非法输入,请检查参数");
            return map;
        }
        Spend model = null;
        try {
            model = spendBusiness.findByOrderCodeAndAmount(orderCode.trim(), amount.trim());
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }
        if (model == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!无法修改");
            return map;
        }
        model.setStatus(status.trim());
        if (!"".equals(message))
            model.setMessage(message);
        try {
            model = spendBusiness.save(model);
        } catch (Exception e) {
            LOG.error("/r/n保存数据异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.修改失败,请重试");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.修改修改成功!");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    /*根据orderSon修改status和message*/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/update/byorderson")
    public @ResponseBody
    Object updateSpendsByOrderSon(
            @RequestParam(value = "orderSon") String orderSon,
            @RequestParam(value = "message") String message,
            @RequestParam(value = "status") String status
    ) {
        Map<String, Object> map = new HashMap<String, Object>();

        Spend model = null;
        try {
            model = spendBusiness.findByorderSon(orderSon);
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }
        if (model == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!无法修改");
            return map;
        }
        model.setStatus(status.trim());
        if (!"".equals(message))
            model.setMessage(message);
        try {
            model = spendBusiness.save(model);
        } catch (Exception e) {
            LOG.error("/r/n保存数据异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.修改失败,请重试");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.修改修改成功!");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    /*根据ordercode和amount增加orderSon*/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/addorder")
    public @ResponseBody
    Object addorderson(
            @RequestParam(value = "orderCode") String orderCode,
            @RequestParam(value = "amount") String amount,
            @RequestParam(value = "orderSon") String orderSon
    ) {
        Map<String, Object> map = new HashMap<String, Object>();

        Spend model = null;
        try {
            model = spendBusiness.findByOrderCodeAndAmount(orderCode.trim(), amount.trim());
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }
        if (model == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!无法修改");
            return map;
        }
        if (!"".equals(orderSon))
            model.setOrderSon(orderSon);
        try {
            model = spendBusiness.save(model);
        } catch (Exception e) {
            LOG.error("/r/n保存数据异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.修改失败,请重试");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.子订单添加成功!");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    /*根据id增加orderSon*/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/addordersonbyid")
    public @ResponseBody
    Object addordersonbyid(
            @RequestParam(value = "id") long id,
            @RequestParam(value = "orderSon") String orderSon
    ) {
        Map<String, Object> map = new HashMap<String, Object>();

        Spend model = null;
        try {
            model = spendBusiness.findById(id);
        } catch (Exception e) {
            LOG.error("/r/n查询异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询数据出错了哦,请重试");
            return map;
        }
        if (model == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.没有查到数据哦!无法修改");
            return map;
        }
        if (!"".equals(orderSon))
            model.setOrderSon(orderSon);
        try {
            model = spendBusiness.save(model);
        } catch (Exception e) {
            LOG.error("/r/n保存数据异常==========" + e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.修改失败,请重试");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "亲.子订单添加成功!");
        map.put(CommonConstants.RESULT, model);
        return map;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/spend/querytaskByBatch")
    public @ResponseBody
    Object queryTaskByBatch(HttpServletRequest request,
                            @RequestParam(value = "batchNo") String batchNo) {
        Map map = new HashMap();

        try {
            List<Spend> task = spendBusiness.queryTaskByBatchNo(batchNo);
            if (task.isEmpty()) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "查询有误");
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                map.put(CommonConstants.RESP_MESSAGE, "查询成功");
                map.put(CommonConstants.RESULT, task);
            }

        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询有误");
        }

        return map;
    }
}
